<?php
/**
 * Used to handle single files
 **/
class Bliss_Media_File
{
	protected $_params = array();
	protected $_path;
	
	public function __construct($path)
	{
		$parts  = explode('.', $path);
		$this->_path = array_shift($parts).'.'.array_pop($parts);
		$this->setParams($parts);
	}
	
	public function compile()
	{
		$ext = pathinfo($this->_path, PATHINFO_EXTENSION);
		$contents = $this->_compile($this->_path, $ext);
		
		if($this->getParam('compressed')) {
			$compression = (string)$this->getParam('compressed') === '1' ? 'simple' : $this->getParam('compressed');
			switch($ext) {
				case 'css':
					$compressor = new Bliss_Media_Compressor_Stylesheet($contents, $compression);
					$contents = $compressor->compress();
					break;
				case 'js':
					$compressor = new Bliss_Media_Compressor_Javascript($contents, $compression);
					$contents = $compressor->compress();
					break;
				default:
					break;
			}
		}
		
		return $contents;
	}

	protected function _compile($path, $ext) {
		$contents = '';
		$list = $this->_compileList($this->_path, $ext);
		foreach($list as $path) {
			$contents .= file_get_contents($path);
		}

		return $contents;
	}
	
	protected function _compileList($path, $ext)
	{
		$files	= array();
		$dirs	= array();

		if(is_file($path)) {
			$files[] = $path;
		}
		
		$info = pathinfo($path);
		$dir = $info['dirname'].'/'.$info['filename'];
		if(is_dir($dir)) {
			foreach(new DirectoryIterator($dir) as $item) {
				if($item->isDot()) continue;
				
				$extension = pathinfo($item->getBasename(), PATHINFO_EXTENSION);
				if($item->isFile() && $extension == $ext) {
					$files[] = $item->getPathName();
				} elseif($item->isDir()) {
					$dirs[] = $item->getPathName();
				}
			}
		}

		foreach($dirs as $dir) {
			$files = array_merge($files, $this->_compileList($dir, $ext));
		}

		return $files;
	}
	
	protected function setParams($data)
	{
		foreach($data as $name) {
			$parts = explode(":", $name);
			$this->_params[$parts[0]] = isset($parts[1]) ? $parts[1] : '1';
		}
	}
	
	protected function hasParam($name)
	{
		return isset($this->_params[$name]);
	}
	
	protected function getParam($name, $default=0)
	{
		return $this->hasParam($name) ? $this->_params[$name] : $default;
	}
}
?>